package com.htstar.ovms.admin.controller;

import com.htstar.ovms.admin.api.dto.MenuTree;
import com.htstar.ovms.admin.api.dto.TreeNode;
import com.htstar.ovms.admin.api.entity.SysMenu;
import com.htstar.ovms.admin.api.entity.SysMenuLang;
import com.htstar.ovms.admin.api.vo.MenuVO;
import com.htstar.ovms.admin.service.SysMenuLangService;
import com.htstar.ovms.admin.service.SysMenuService;
import com.htstar.ovms.common.core.util.R;
import com.htstar.ovms.common.log.annotation.SysLog;
import com.htstar.ovms.common.security.util.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;


import javax.validation.Valid;
import java.util.HashSet;

import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author ovms
 * @date 2017/10/31
 */
@RestController
@AllArgsConstructor
@RequestMapping("/menu")
@Api(value = "menu", tags = "菜单管理模块")
@Slf4j
public class SysMenuController {
    private final SysMenuService sysMenuService;
    private final SysMenuLangService sysMenuLangService;

    /**
     * 返回当前用户的树形菜单集合
     *
     * @param type     类型
     * @param parentId 父节点ID
     * @return 当前用户的树形菜单
     */
    @GetMapping
    public R getUserMenu(String type, Integer parentId) {
        // 获取符合条件的菜单
        Set<MenuVO> all = new HashSet<>();
        SecurityUtils.getRoles()
                .forEach(roleId -> all.addAll(sysMenuService.findMenuByRoleId(roleId)));
        List<MenuTree> menuTrees = sysMenuService.filterMenu(all, type, parentId);
        //翻译工作
        List<SysMenuLang> langTable = sysMenuLangService.getLangTable();
        String language = LocaleContextHolder.getLocale().getLanguage();
        for (MenuTree menu : menuTrees) {
            String menuNameTrans = getMenuName(menu.getName(), language, langTable);
            menu.setName(menuNameTrans);//进行翻译
            menu.setLabel(menuNameTrans);
            if (menu.getChildren() != null) {//有子项的情况
                List<TreeNode> children = menu.getChildren();
                for (TreeNode child : children) {//对每一个子项翻译
                    MenuTree childrenItem = (MenuTree) child;
                    String childrenMenuNameTrans = getMenuName(childrenItem.getName(), language, langTable);
                    childrenItem.setName(childrenMenuNameTrans);
                    childrenItem.setLabel(childrenMenuNameTrans);
                }
            }
        }
        return R.ok(menuTrees);
    }

    private String getMenuName(String menuName, String lang, List<SysMenuLang> tab) {
        String trans = null;
        for (SysMenuLang tabItem : tab) {
            if (tabItem.getMenuName().equals(menuName)) {
                switch (lang) {
                    case "en":
                        trans = tabItem.getMenuEn();
                        break;
                    case "tw":
                        trans = tabItem.getMenuTw();
                        break;
                }
            }
        }
        return trans == null ? menuName : trans;
    }

    /**
     * 返回树形菜单集合
     *
     * @param lazy     是否是懒加载
     * @param parentId 父节点ID
     * @return 树形菜单
     */
    @GetMapping(value = "/tree")
    public R getTree(boolean lazy, Integer parentId) {
        return R.ok(sysMenuService.treeMenu(lazy, parentId));
    }

    @GetMapping("/appMenuTree")
    @ApiOperation(value = "企业app端菜单树", notes = "企业app端菜单树")
    public R getAppMenuName() {
        return R.ok(sysMenuService.getAppMenuTree());
    }

    /**
     * 返回角色的菜单集合
     *
     * @param roleId 角色ID
     * @return 属性集合
     */
    @GetMapping("/tree/{roleId}")
    public R getRoleTree(@PathVariable Integer roleId) {
        return R.ok(sysMenuService.findMenuByRoleId(roleId)
                .stream()
                .map(MenuVO::getMenuId)
                .collect(Collectors.toList()));
    }

    /**
     * 通过ID查询菜单的详细信息
     *
     * @param id 菜单ID
     * @return 菜单详细信息
     */
    @GetMapping("/{id}")
    public R getById(@PathVariable Integer id) {
        return R.ok(sysMenuService.getById(id));
    }

    /**
     * 新增菜单
     *
     * @param sysMenu 菜单信息
     * @return success/false
     */
    @SysLog("新增菜单")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('sys_menu_add')")
    public R save(@Valid @RequestBody SysMenu sysMenu) {
        sysMenuService.save(sysMenu);
        return R.ok(sysMenu);
    }

    /**
     * 删除菜单
     *
     * @param id 菜单ID
     * @return success/false
     */
    @SysLog("删除菜单")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('sys_menu_del')")
    public R removeById(@PathVariable Integer id) {
        return sysMenuService.removeMenuById(id);
    }

    /**
     * 更新菜单
     *
     * @param sysMenu
     * @return
     */
    @SysLog("更新菜单")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('sys_menu_edit')")
    public R update(@Valid @RequestBody SysMenu sysMenu) {
        return R.ok(sysMenuService.updateMenuById(sysMenu));
    }

}
